﻿using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using Assets.AnimationPlayer.Scripts.Animations;
using Assets.AnimationPlayer.Scripts.Prefabs;
using Assets.AnimationPlayer.Scripts.Util;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Assets.AnimationPlayer.Scripts.UI
{
    public class UiAnimationListView : MonoBehaviour
    {
        public AnimationListSubPage TopPage;
        public AnimationListSubPage RightPage;
        public AnimationListSubPage LeftPage;

        internal void Awake()
        {
            _loadAnimationConfigXml();
            _init();
        }

        // Use this for initialization
        internal void _init()
        {
            if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex == -1 &&
                AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count > 0)
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex = 0;
            }

            if(AnimationVar.UnDestoryScene.CallApi.AutoPlayModel)
            {
                TopPage.LoadingView.SetActive(false);
                RightPage.LoadingView.SetActive(false);
                LeftPage.LoadingView.SetActive(false);
            }
            else
            {
                TopPage.LoadingView.SetActive(true);
                RightPage.LoadingView.SetActive(true);
                LeftPage.LoadingView.SetActive(true);
            }

            if (AnimationVar.AnimationPlayCfg.AutoPlay)
            {


                AnimationVar.AnimationPlayCfg.AutoPlay = false;
                AnimationVar.UnDestoryScene.CallApi.API_LoadingComplete();
                AnimationVar.PlayAnimation();
            }
            else
            {
                TopPage.TopBarControl.ShowLogo(AnimationVar.AnimationPlayCfg.ColorLogoType);
                RightPage.TopBarControl.ShowLogo(AnimationVar.AnimationPlayCfg.ColorLogoType);
                LeftPage.TopBarControl.ShowLogo(AnimationVar.AnimationPlayCfg.ColorLogoType);

                TopPage.BindClickEvents(_showQuitNotice, _itemClick);
                TopPage.BindMessageBoxEvents(_exitApp, _hideQuitNotice);
                RightPage.BindClickEvents(_showQuitNotice, _itemClick);
                RightPage.BindMessageBoxEvents(_exitApp, _hideQuitNotice);
                LeftPage.BindClickEvents(_showQuitNotice, _itemClick);
                LeftPage.BindMessageBoxEvents(_exitApp, _hideQuitNotice);

                _reloadAnimationList();
            }
        }




        #region ClickEvents
        /// <summary>
        /// 大图点击，播放动画
        /// </summary>
        /// <param name="typeStr"></param>
        private void _itemClick(string typeStr)
        {
            if (typeStr == "left")
            {
                _leftButtonClick();
            }
            else if (typeStr == "right")
            {
                _rightButtonClick();
            }
            else
            {
                try
                {
                    AnimationVar.AnimationPlayCfg.SelectAnimationIndex = int.Parse(typeStr);
                }
                catch
                {
                    AnimationVar.AnimationPlayCfg.SelectAnimationIndex = 0;
                }
   
                AnimationVar.PlayAnimation();
            }
        }

        private static void _exitApp()
        {
            Application.Quit();
            AnimationVar.UnDestoryScene.CallApi.API_Break();
        }

        #endregion

        #region QuitNotice 退出提示
        /// <summary>
        /// 
        /// </summary>
        private void _hideQuitNotice()
        {
            TopPage.MessageBox.gameObject.SetActive(false);
            RightPage.MessageBox.gameObject.SetActive(false);
            LeftPage.MessageBox.gameObject.SetActive(false);
        }
        private void _showQuitNotice()
        {
            TopPage.MessageBox.ResetSelect();
            TopPage.MessageBox.gameObject.SetActive(true);
            RightPage.MessageBox.ResetSelect();
            RightPage.MessageBox.gameObject.SetActive(true);
            LeftPage.MessageBox.ResetSelect();
            LeftPage.MessageBox.gameObject.SetActive(true);
        }

        private bool QuitNoticeShowing
        {
            get
            {
                return TopPage.MessageBox.gameObject.activeInHierarchy ||
                RightPage.MessageBox.gameObject.activeInHierarchy ||
                LeftPage.MessageBox.gameObject.activeInHierarchy;
            }
        }

        #endregion


        #region 左右箭头点击事件
        private void _leftButtonClick()
        {
            _leftButtonClickStyle();
            _leftClick();

        }
        private void _rightButtonClick()
        {
            _rightButtonClickStyle();
            _rightClick();
        }

        #endregion

        #region 左右箭头特效
        private void _leftButtonClickStyle()
        {
            ExecuteEvents.Execute(TopPage.MainContentControl.BtnLeftArrow, new PointerEventData(EventSystem.current), ExecuteEvents.submitHandler);
            ExecuteEvents.Execute(RightPage.MainContentControl.BtnLeftArrow, new PointerEventData(EventSystem.current), ExecuteEvents.submitHandler);
            ExecuteEvents.Execute(LeftPage.MainContentControl.BtnLeftArrow, new PointerEventData(EventSystem.current), ExecuteEvents.submitHandler);
        }
        private void _rightButtonClickStyle()
        {
            ExecuteEvents.Execute(TopPage.MainContentControl.BtnRightArrow, new PointerEventData(EventSystem.current), ExecuteEvents.submitHandler);
            ExecuteEvents.Execute(RightPage.MainContentControl.BtnRightArrow, new PointerEventData(EventSystem.current), ExecuteEvents.submitHandler);
            ExecuteEvents.Execute(LeftPage.MainContentControl.BtnRightArrow, new PointerEventData(EventSystem.current), ExecuteEvents.submitHandler);
        }

        #endregion


        // Update is called once per frame

        private int _arrowH; //-1,0,1分别代表左中右
        private int _arrowV ; //1,0,-1分别代表上中下
        internal void Update()
        {
            if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex == -1) return;
            if (QuitNoticeShowing) return;
            if (Input.anyKeyDown)
            {
                if (Input.GetKey(KeyCode.JoystickButton0) ||
                    Input.GetKey(KeyCode.Joystick1Button0) ||
                    Input.GetKey(KeyCode.Joystick2Button0) ||
                    Input.GetKey(KeyCode.Joystick3Button0) ||
                    Input.GetKey(KeyCode.Joystick4Button0) ||
                    Input.GetKey(KeyCode.Joystick5Button0) ||
                    Input.GetKey(KeyCode.Joystick6Button0) ||
                    Input.GetKey(KeyCode.Joystick7Button0) ||
                    Input.GetKey(KeyCode.Joystick8Button0) ||
                    Input.GetKey(KeyCode.Return) ||
                    Input.GetKey((KeyCode)10))
                {
                    //确定
                    //Debug.Log("确定");
                    AnimationVar.PlayAnimation();
                }

                if (Input.GetKey(KeyCode.JoystickButton1) ||
                    Input.GetKey(KeyCode.Joystick1Button1) ||
                    Input.GetKey(KeyCode.Joystick2Button1) ||
                    Input.GetKey(KeyCode.Joystick3Button1) ||
                    Input.GetKey(KeyCode.Joystick4Button1) ||
                    Input.GetKey(KeyCode.Joystick5Button1) ||
                    Input.GetKey(KeyCode.Joystick6Button1) ||
                    Input.GetKey(KeyCode.Joystick7Button1) ||
                    Input.GetKey(KeyCode.Joystick8Button1) ||
                    Input.GetKey(KeyCode.Escape))
                {
                    _showQuitNotice();
                    //Debug.Log("退出");
                }

                if (Input.GetKey(KeyCode.JoystickButton3) ||
                    Input.GetKey(KeyCode.Joystick1Button3) ||
                    Input.GetKey(KeyCode.Joystick2Button3) ||
                    Input.GetKey(KeyCode.Joystick3Button3) ||
                    Input.GetKey(KeyCode.Joystick4Button3) ||
                    Input.GetKey(KeyCode.Joystick5Button3) ||
                    Input.GetKey(KeyCode.Joystick6Button3) ||
                    Input.GetKey(KeyCode.Joystick7Button3) ||
                    Input.GetKey(KeyCode.Joystick8Button3) ||
                    Input.GetKey(KeyCode.Space))
                {
                    _showQuitNotice();
                    //Debug.Log("退出");
                }
            }

            //设置选择 项 selectView
            float horizontalAxis = Input.GetAxis("Horizontal");
            if (Math.Abs(horizontalAxis) > 0)
            {
                if (horizontalAxis > 0)
                {
                    if (_arrowH == 1)
                    {
                        return;
                    }
                    else
                    {
                        _arrowH = 1;
                    }
                    _rightButtonClick();
                }
                else
                {
                    if (_arrowH == -1)
                    {
                        return;
                    }
                    else
                    {
                        _arrowH = -1;
                    }
                    _leftButtonClick();
                }
            }
            else
            {
                if(_arrowH != 0)
                    _arrowH = 0;
                else
                {
                }
            }

            float verticalAxis = Input.GetAxis("Vertical");
            if (Math.Abs(verticalAxis) > 0)
            {
                if (verticalAxis > 0)
                {
                    if (_arrowV == 1)
                    {
                        return;
                    }
                    else
                    {
                        _arrowV = 1;
                    }
                    _topClick();
                }
                else
                {
                    if (_arrowV == -1)
                    {
                        return;
                    }
                    else
                    {
                        _arrowV = -1;
                    }
                    _bottomClick();
                }
            }
            else
            {
                _arrowV = 0;
            }
        }

        private void _leftClick()
        {
            //向左
            if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex > 0)
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex--;
                StartCoroutine(_upAnimationsStyle(true));
            }
            else if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex == 0)
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex = AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count - 1;
                StartCoroutine(_upAnimationsStyle(true, true));
            }
        }
        private void _rightClick()
        {
            //Debug.Log("向右");
            //向右
            if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex < AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count - 1)
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex++;
                StartCoroutine(_upAnimationsStyle(true, true));
            }
            else if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex == AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count - 1)
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex = 0;
                StartCoroutine(_upAnimationsStyle(true));
            }
        }
        private void _bottomClick()
        {
            _rightButtonClick(); return;
            if (AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count > AnimationListSubPage.ClumnCount)
            {
                if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex + AnimationListSubPage.ClumnCount >= AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count)
                {
                    if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex > (AnimationListSubPage.RowsCount - 1) * AnimationListSubPage.ClumnCount - 1)
                    {
                        AnimationVar.AnimationPlayCfg.SelectAnimationIndex = AnimationVar.AnimationPlayCfg.SelectAnimationIndex % AnimationListSubPage.ClumnCount;
                    }
                    else
                    {
                        AnimationVar.AnimationPlayCfg.SelectAnimationIndex = AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count - 1;
                    }
                    StartCoroutine(_upAnimationsStyle(true, true));
                }
                else
                {
                    AnimationVar.AnimationPlayCfg.SelectAnimationIndex += AnimationListSubPage.ClumnCount;
                    StartCoroutine(_upAnimationsStyle(true, false));
                }

            }
        }
        private void _topClick()
        {
            _leftButtonClick(); return;
            //向上
            if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex > AnimationListSubPage.ClumnCount - 1)
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex -= AnimationListSubPage.ClumnCount;
                StartCoroutine(_upAnimationsStyle(true, true));
            }
            else
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex += (AnimationListSubPage.RowsCount - 1) * AnimationListSubPage.ClumnCount;
                if (AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count - 1 < AnimationVar.AnimationPlayCfg.SelectAnimationIndex)
                {
                    AnimationVar.AnimationPlayCfg.SelectAnimationIndex = AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count - 1;
                }
                StartCoroutine(_upAnimationsStyle(true, false));
            }
        }

        private void _reloadAnimationList()
        {
            if (AnimationVar.AnimationPlayCfg.SelectAnimationIndex == -1 && AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count > 0)
            {
                AnimationVar.AnimationPlayCfg.SelectAnimationIndex = 0;
            }
            StartCoroutine(_loadAnimationList());
        }

        private IEnumerator _loadAnimationList()
        {
            AnimationListSubPage.RowsCount = 1;
            yield return new WaitForEndOfFrame();
            var isShowNocontent = AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count <= 0;
            TopPage.MainContentControl.NoneContentView.SetActive(isShowNocontent);
            RightPage.MainContentControl.NoneContentView.SetActive(isShowNocontent);
            LeftPage.MainContentControl.NoneContentView.SetActive(isShowNocontent);

            int i = 0;
            AnimationListSubPage.ClumnCount = Math.Max(AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count, 1);
            foreach (var animationObj in AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs)
            {
                int index = (i % AnimationListSubPage.ClumnCount);
                if (string.IsNullOrEmpty(animationObj.AnimationPath))
                {
                    continue;
                }
                _upAnimation(TopPage.ItemListScrollRect, "animation_" + i, i, index, AnimationListSubPage.RowsCount - 1, animationObj, 0, -1);
                _upAnimation(RightPage.ItemListScrollRect, "animation_" + i, i, index, AnimationListSubPage.RowsCount - 1, animationObj, -90, 1, -1);
                _upAnimation(LeftPage.ItemListScrollRect, "animation_" + i, i, index, AnimationListSubPage.RowsCount - 1, animationObj, 90, 1, -1);
                if (index == AnimationListSubPage.ClumnCount - 1 && i != AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count - 1) AnimationListSubPage.RowsCount++;
                i++;
            }

            TopPage.ResetItemsContainerSize();
            RightPage.ResetItemsContainerSize();
            LeftPage.ResetItemsContainerSize();

            StartCoroutine(_upAnimationsStyle());
            AnimationVar.UnDestoryScene.CallApi.API_LoadingComplete();
        }

        private static void _upAnimation(MyScrollRect scrollRect, string id, int index, int x, int y, AnimationObj animationObj, float angleZ = 0, float factorY = 1, float factorX = 1)
        {
            GameObject game;
            if (scrollRect.content.Find(id) != null)
                game = scrollRect.content.Find(id).gameObject;
            else
            {
                game = Instantiate(Resources.Load<GameObject>("Prefabs/AnimationItem"), scrollRect.content);
                game.transform.Rotate(0, 0, angleZ);
                var vector3 = game.transform.localScale;
                vector3.x *= factorX;
                vector3.y *= factorY;
                game.transform.localScale = vector3;
                //game.transform.SetParent(scrollRect.content);
            }
            game.name = id;
            game.SetActive(true);
            game.GetComponent<RectTransform>().anchoredPosition = new Vector2(x * 280 + (x + 1) * 20, 0 - (y * 180 + (y + 1) * 15));
            game.GetComponent<AnimationItem>().SetItem(animationObj, index, scrollRect);
        }

        private IEnumerator _upAnimationsStyle(bool isScroll = false, bool leftToright = false)
        {
            TopPage.UpAnimationItemsStyle(isScroll, leftToright);
            RightPage.UpAnimationItemsStyle(isScroll, leftToright);
            LeftPage.UpAnimationItemsStyle(isScroll, leftToright);
            yield return new WaitForEndOfFrame();
        }

        private static void _loadAnimationConfigXml()
        {
            if (AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs.Count > 0) return;
            var textAsset = Resources.Load("cfg15", typeof(TextAsset)) as TextAsset;
           // var textAsset = Resources.Load("cfg_all_right", typeof(TextAsset)) as TextAsset;
            if (textAsset != null)
            {
                var xmlContent = string.IsNullOrEmpty(textAsset.text) ? "" : textAsset.text;
                //replale 注释
                //string reg = "<!--level[0-9]{1,}-->";//level1,level2 ...
                var reg = "<!--level[0-9]{1,}[ ]{0,}([a-z]|[A-Z]){0,}-->";//level1 start,level1 end ...
                xmlContent = Regex.Replace(xmlContent, reg, "");
                AnimationVar.AnimationPlayCfg.Cfg = AnimationCfg.Get(xmlContent);
                var str = new StringBuilder();
                foreach (var cfgAnimationObj in AnimationVar.AnimationPlayCfg.Cfg.AnimationObjs)
                {
                    str.Append(cfgAnimationObj.AnimationName + "\r\n");
                }
                Debug.Log(str.ToString());
            }
        }
    }
}
